﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Diagnostics;
using Code4WP7SDK;
using Newtonsoft.Json;
using LuWeibo.Models;
using LuWeiboSDK;

namespace LuWeibo
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            string access_token = (string)IsoStorageHelper.GetValueFromSettings("access_token");
            if (string.IsNullOrEmpty(access_token))
            {
                string loginUrl = string.Format("{0}{1}client_id={2}&response_type={3}&redirect_uri={4}&display={5}",
                Constant.AuthorizeUrl, Constant.Mark, Constant.Appkey, Constant.CodeResponseType, Constant.RedirectUrl, Constant.DisplayType);
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    LoginBrowser.Navigate(new Uri(loginUrl, UriKind.Absolute));
                });
            }
            else
            {
                Constant.AccessToken = access_token;
                NavigateToLuHomePage();
            }
            base.OnNavigatedTo(e);
        }

        private void LoginBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
        }

        private void LoginBrowser_Navigating(object sender, NavigatingEventArgs e)
        {
            string codeUrl = string.Concat(Constant.RedirectUrl,"/",Constant.Mark, Constant.CodeResponseType);
            if (e.Uri.AbsoluteUri.Contains(codeUrl))
            {
                //e.Cancel = true;
                List<Parameter> parameters = ParameterHelper.GetParametersFromUrl(e.Uri.AbsoluteUri);
                string data = string.Format
                    ("client_id={0}&client_secret={1}&grant_type={2}&redirect_uri={3}&code={4}", Constant.Appkey, Constant.AppSecret, Constant.TokenResponseType, Constant.RedirectUrl, parameters[0].Value);
                WebClientService ws = new WebClientService();
                ws.WebClientCompleted += ws_WebClientCompleted;
                ws.PostRequest(Constant.AccessTokenUrl, data);
            }
        }

        void ws_WebClientCompleted(object sender, WebClientCompletedEventArgs e)
        {
            if (e.Ex == null)
            {
                Debug.WriteLine(e.Result.ToString());
                AccessTokenModel tokenModel = JsonConvert.DeserializeObject<AccessTokenModel>(e.Result.ToString());
                //写入静态变量中
                Constant.AccessToken = tokenModel.access_token;
                //存入IsolatedStorage
                IsoStorageHelper.SaveInToSettings("access_token", Constant.AccessToken);
                NavigateToLuHomePage();
            }
            else
            {
                //TODO 异常处理
            }
        }

        public void NavigateToLuHomePage()
        {
            this.NavigationService.Navigate(new Uri("/Views/LuHomePage.xaml", UriKind.Relative));
        }

        private void LoginBrowser_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                LoginBrowser.InvokeScript("eval",
                @"
                window.ScanTelTag=function(elem) {
                if (elem.getAttribute('target') != null && elem.getAttribute('target').indexOf('_parent') == 0) {
                    elem.setAttribute('target', '_self');
                    }
                }
            
                window.Initialize=function() {
                var elems = document.getElementsByTagName('a');
                for (var i = 0; i < elems.length; i++)
                ScanTelTag(elems[i]);
                }");
                LoginBrowser.InvokeScript("Initialize");
            }
            catch (Exception)
            {

            }
        }

        private void LoginBrowser_NavigationFailed(object sender, System.Windows.Navigation.NavigationFailedEventArgs e)
        {
            //Debug.WriteLine("Exception:" + e.Exception.ToString());
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);
            //TODO 返回键处理
        }
    }
}